<template>
  <div>
    <el-button type="text" @click="isShow = true">添加学生</el-button>
    <el-table :data="studentArray" border style="width: 500px">
      <el-table-column prop="id" label="编号" width="120"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="age" label="年龄" width="120"></el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button @click="delStudentArray(scope.row.id)" type="text" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="添加學生信息" :visible.sync="isShow" width="30%">
      <el-form>
        <el-form-item label="id">
          <el-input v-model="form.id"></el-input>
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="年齡">
          <el-input v-model="form.age"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isShow = false">取 消</el-button>
        <el-button type="primary" @click="setStudentArray">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
export default {
  data() {
    return {
      studentArray: [],
      isShow: false,
      form:{
        id:"",
        name:"",
        age:""
      }
    };
  },
  methods: {
    delStudentArray(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          axios.delete(`http://127.0.0.1:3000/${id}`).then(() => {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getStudentArray();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    getStudentArray() {
      axios.get("http://127.0.0.1:3000").then((res) => {
        this.studentArray = res.data;
      });
    },
    setStudentArray(){
      axios.post("http://127.0.0.1:3000",{student:this.form})
      .then(() => {
        this.getStudentArray();
        this.isShow=false;
        this.form={id:"",name:"",age:""}
      })
    }
  },
  created() {
    this.getStudentArray();
  },
};
</script>
